package com.example.yichuangyun.mvvm.ui.activity;

import android.os.Bundle;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityContactsDetailsBinding;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.model.EventBusModel;
import com.example.yichuangyun.model.business.CompanyModel;
import com.example.yichuangyun.model.call.TabModel;
import com.example.yichuangyun.model.contacts.AddContactsParamsModel;
import com.example.yichuangyun.model.contacts.ContactWayModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.view.ContactsDetailsViewModel;
import com.example.yichuangyun.mvvm.ui.adapter.CompanyNameAdapter;
import com.example.yichuangyun.mvvm.ui.fragment.BusinessRecordFragment;
import com.example.yichuangyun.mvvm.ui.fragment.ContactsDataDetailsFragment;
import com.example.yichuangyun.mvvm.ui.fragment.ContactsDetailsCallRecordFragment;
import com.example.yichuangyun.mvvm.ui.fragment.ContactsDetailsFollowRecordFragment;
import com.example.yichuangyun.ui.activity.business.AddBusinessActivity;
import com.example.yichuangyun.ui.activity.follow.AddFollowActivity;
import com.example.yichuangyun.ui.adapter.ViewPagerAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.RequestUtils;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 联系人详情
 */
public class ContactsDetailsActivity extends BaseActivity<ActivityContactsDetailsBinding, ContactsDetailsViewModel> {

    private final ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private String[] titles;
    private final List<Fragment> fragments = new ArrayList<>();
    private String contactId;
    private final List<String> tels = new ArrayList<>();
    private String mTelNumber;
    private String clientName;
    private boolean isCalling;
    private MyDialog myDialog;
    private AddContactsParamsModel mModel;
    private final List<String> progressTitle = new ArrayList<>();
    private boolean firstRefresh = true;
    private int contactType;

    @Override
    protected ContactsDetailsViewModel bindModel() {
        return getViewModel(this, ContactsDetailsViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (isCalling && mTelNumber != null) {
            isCalling = false;
            RequestUtils.addContactsFollow(contactId, clientName, mTelNumber);
        }
    }

    @Override
    protected void initData() {
        initTitleBar(getString(R.string.contacts_details));
        initDialog();
        titles = new String[]{getString(R.string.follow_record), getString(R.string.call_record), getString(R.string.business_record), getString(R.string.contacts_info_details)};
        for (String title : titles) {
            mTabEntities.add(new TabModel(title));
        }
        progressTitle.add(getString(R.string.not_follow));
        progressTitle.add(getString(R.string.following));
        progressTitle.add(getString(R.string.already_transform));

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            contactId = bundle.getString(Constant.idKey);
            contactType = bundle.getInt(Constant.contactTypeKey);
            showLoadingDialog();
            viewModel.getContactsDetails(contactId, contactType);
        }
    }

    @Override
    protected void initClick() {
        viewModel.detailsModel.observe(this, model -> {
            dismissLoadingDialog();
            mModel = model;
            clientName = model.getUsername();
            binding.tvContactName.setText(CommonUtil.checkText(clientName));
            binding.tvNextFollowTime.setText(CommonUtil.setYHMTime(model.getNextFollowTime()));
            final Set<Integer> set = new HashSet<>();
            int progressSize = progressTitle.indexOf(model.getFollowStatusName());
            for (int i = 0; i <= progressSize; i++) {
                set.add(i);
            }
            binding.progressBar.setNodeData(progressTitle, set);
            List<CompanyModel> companyList = model.getCompNameList();
            if (null != companyList && companyList.size() > 0) {
                binding.tvNull.setVisibility(View.GONE);
                binding.recyclerView.setAdapter(new CompanyNameAdapter(context, companyList));
            } else {
                binding.tvNull.setVisibility(View.VISIBLE);
            }

            List<ContactWayModel> contactsWayList = model.getTels();
            if (null != contactsWayList && !contactsWayList.isEmpty()) {
                tels.clear();
                for (ContactWayModel contactWayModel : contactsWayList) {
                    if (contactWayModel.getType() == 1) {
                        tels.add(contactWayModel.getInfo());
                    }
                }
                if (tels.size() == 1) {
                    mTelNumber = tels.get(0);
                }
            }
            if (firstRefresh) {
                initFragment();
                firstRefresh = false;
            }
            binding.smartRefreshLayout.finishRefresh();
        });

        viewModel.mErrorData.observe(this, s -> {
            binding.smartRefreshLayout.finishRefresh();
            dismissLoadingDialog();
        });

        viewModel.onDelayClick(binding.llAddFollow, o -> {
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.flagKey, 1);
            bundle.putString(Constant.businessIdKey, mModel.getId());
            bundle.putString(Constant.nameKey, mModel.getUsername());
            bundle.putStringArrayList(Constant.telKey, (ArrayList<String>) tels);
            JumpIntent.jump(ContactsDetailsActivity.this, AddFollowActivity.class, bundle);
        });

        viewModel.onDelayClick(binding.llEdit, o -> {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.idKey, mModel.getId());
            bundle.putInt(Constant.flagKey, 1);
            bundle.putInt(Constant.contactTypeKey, contactType);
            JumpIntent.jump(ContactsDetailsActivity.this, AddContactsActivity.class, bundle);
        });

        viewModel.onDelayClick(binding.llTransform, o -> {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.idKey, mModel.getId());
            bundle.putString(Constant.nameKey, mModel.getUsername());
            bundle.putInt(Constant.sexKey, mModel.getSex());
            bundle.putSerializable(Constant.listKey, (Serializable) mModel.getTels());
            JumpIntent.jump(ContactsDetailsActivity.this, AddBusinessActivity.class, bundle);
        });

        viewModel.onDelayClick(binding.llCall, o -> {
            if (tels.size() == 1) {
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, true);
            } else {
                initSinglePickerView(tels, getString(R.string.call_num));
            }
        });

        binding.smartRefreshLayout.setOnRefreshListener(refreshLayout -> viewModel.getContactsDetails(contactId, contactType));

        binding.viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                binding.tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        binding.tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                binding.viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
    }

    private void initSinglePickerView(List<String> data, String title) {
        SinglePickerView singlePickerView = new SinglePickerView(this, title, data) {
            @Override
            public void confirm(String label, int position) {
                mTelNumber = label;
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, true);
            }
        };
        singlePickerView.showSinglePickerView();
    }

    private void initDialog() {
        myDialog = new MyDialog(this) {
            @Override
            public void leftClick() {
                RequestUtils.callNum(context, mTelNumber);
                Constant.pushBusinessId = "1";
                isCalling = true;
            }

            @Override
            public void rightClick() {
                RequestUtils.callbackOutbound2(context, mTelNumber, contactId, clientName);
            }
        };
    }

    private void initFragment() {
        fragments.add(ContactsDetailsFollowRecordFragment.newInstance(contactId));
        fragments.add(ContactsDetailsCallRecordFragment.newInstance(contactId, clientName));
        fragments.add(BusinessRecordFragment.newInstance(contactId, contactType));
        fragments.add(ContactsDataDetailsFragment.newInstance(contactId, contactType));
        binding.viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), 0, titles, fragments));
        binding.tabLayout.setTabData(mTabEntities);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (eventBusModel.getMsg().equals(Constant.refreshContactDetailsData)) {
                viewModel.getContactsDetails(contactId, contactType);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}